package com.joro.ejb;

import java.util.Collection;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.app.LoggingUtil;
import com.joro.Magazine;

/**
 * Session Bean implementation class MyFacade
 */
@WebService
@Stateless
@LocalBean
public class MagazineFacade implements MagazineFacadeLocal {

	@PersistenceContext(unitName = "magazine.ejb")
	EntityManager manager;

	/**
	 * Default constructor.
	 */
	public MagazineFacade() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void saveMagazine(Magazine pMagazine){
		LoggingUtil.logOperation(LoggingUtil.OPERATION_UPDATE, pMagazine);
		manager.merge(pMagazine);
	}
	
	@Override
	public void createMagazine(String pName, int pPeriod, double pPrice){
		Magazine lMagazine = new Magazine();
		lMagazine.setName(pName);
		lMagazine.setPeriod(pPeriod);
		lMagazine.setPrice(pPrice);
		LoggingUtil.logOperation(LoggingUtil.OPERATION_CREATE, lMagazine);
		this.saveMagazine(lMagazine);
	}
	
	@Override
	public Collection<Magazine> getMagazines(){
		Query query = manager.createQuery("SELECT e FROM Magazine e");
		List<Magazine> resultList = query.getResultList();
		return resultList;
	}
	
	public Magazine getMagazineById(int pMagazineId){
		Query query = manager.createQuery("SELECT e FROM Magazine e WHERE e.id = ?1");
		query.setParameter(1, pMagazineId);
		List<Magazine> resultList = query.getResultList();
		return resultList.get(0);
	}

	@Override
	public void deleteMagazine(Magazine pMagazine) {
		Query query = manager.createQuery("SELECT e FROM Subscription e WHERE e.magazine = ?1");
		query.setParameter(1, pMagazine);
		List<Magazine> resultList = query.getResultList();
		if(!resultList.isEmpty()){
			throw new RuntimeException("You cannot delete this magazine, because there are subscriptions referencing it");
		}
		LoggingUtil.logOperation(LoggingUtil.OPERATION_DELETE, pMagazine);
		manager.remove(manager.contains(pMagazine) ? pMagazine : manager.merge(pMagazine));		
	}
}
